package com.stone.EasyTeaching.view;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.stone.EasyTeaching.ETApplication;
import com.stone.EasyTeaching.R;
import com.stone.EasyTeaching.events.BaseEvents;
import com.stone.EasyTeaching.events.EventsConfig;
import com.stone.EasyTeaching.models.AlbumModel;
import com.stone.EasyTeaching.utilities.AlbumDetailFragment;
import com.stone.EasyTeaching.utilities.AlbumList;
import com.stone.EasyTeaching.utilities.HackyViewPager;
import de.greenrobot.event.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hangli2 on 2015/3/25.
 */
public class PreView extends FragmentActivity implements View.OnClickListener{

    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    public static final String EXTRA_IMAGE_ARRAYS = "image_arrays";
    /**
     * Application
     */
    private ETApplication app;
    /**
     * 异步请求Client
     */
    private AsyncHttpClient client;
    /**
     * 展示图片pager
     */
    private HackyViewPager mPager;
    /*图片索引*/
    private TextView tvPicIndex;
    /*底部按钮*/
    private RelativeLayout layoutBottom;
    /**/
    private ImagePagerAdapter mAdapter;

    public static PreView intance;
    //传进来的索引
    private int index;

    private List<AlbumModel> albumModelList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (ETApplication) this.getApplicationContext();
        client = app.getClient();
        EventBus.getDefault().register(this);
        intance = this;
        index = getIntent().getIntExtra("index",0);
        init();
        listener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化ui
     */
    public void init() {
        setContentView(R.layout.pre_view_layout);
        tvPicIndex = (TextView) findViewById(R.id.question_detail_pic_index);
        layoutBottom = (RelativeLayout) findViewById(R.id.bottom_banner);

        mPager = (HackyViewPager) findViewById(R.id.question_detail_pager);
        mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), AlbumList.getAlbumModelList());
        mPager.setAdapter(mAdapter);
        if (AlbumList.getAlbumModelList().get(0)==null){
            index -= 1;
        }
        CharSequence text = getString(R.string.viewpager_indicator,index+1, mPager.getAdapter().getCount());
        tvPicIndex.setText(text);
        mPager.setCurrentItem(index);
    }

    public void listener(){
        findViewById(R.id.top_button_left).setOnClickListener(this);
        findViewById(R.id.delete).setOnClickListener(this);
        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
            }

            @Override
            public void onPageSelected(int i) {
//                Toast.makeText(PreView.this,i+"",Toast.LENGTH_SHORT).show();
                int count = mPager.getAdapter().getCount();
                index = i;
                CharSequence text = getString(R.string.viewpager_indicator, i+1, count);
                tvPicIndex.setText(text);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
//                Toast.makeText(PreView.this,i+"",Toast.LENGTH_SHORT).show();
//                index = i;
            }
        });
    }
    /**
     * 响应按键事件. 在主页面按退出后退出程序前判断
     *
     * @param keyCode 按键码
     * @param event   事件
     * @return 是否消费事件
     */
    public final boolean onKeyDown(final int keyCode, final KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.top_button_left:
                this.finish();
                break;
            case R.id.delete:
                ArrayList<AlbumModel> list = AlbumList.getAlbumModelList();
                list.remove(index);
                if (list.size() == 0||(list.size() == 1&& list.get(0) == null)){
                    finish();
                    return;
                }
                mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), AlbumList.getAlbumModelList());
                mPager.setAdapter(mAdapter);
                if (index == mPager.getAdapter().getCount()){
                    index --;
                }
                if (mPager.getAdapter().getCount() == 0){
                    finish();
                }
                mPager.setCurrentItem(index);
                CharSequence text = getString(R.string.viewpager_indicator,index+1, mPager.getAdapter().getCount());
                tvPicIndex.setText(text);
                break;
            default:
                break;
        }
    }

    /**
     * 图片适配器
     */
    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

        public ArrayList<AlbumModel> fileList;

        public ImagePagerAdapter(FragmentManager fm, ArrayList<AlbumModel> list) {
            super(fm);
            this.fileList = (ArrayList<AlbumModel>) list.clone();
//            this.fileList = list;
            if (fileList.get(fileList.size()-1) == null){
                fileList.remove(fileList.size()-1);
            }
        }

        @Override
        public int getCount() {
            return fileList == null ? 0 : fileList.size();
        }

        @Override
        public Fragment getItem(int position) {
            String url = "";
            try {
                url = fileList.get(position).getUrl();
//                if (url == null){
//                    return null;
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return AlbumDetailFragment.newInstance(url, false);
        }
    }

    public static void kill(){
        intance.finish();
    }

    /************************** EventBus事件 ********************************/
    /**
     * 异步消息响应线程
     *
     * @param event
     */
    @SuppressWarnings("unchecked")
    public void onEventAsync(BaseEvents event) throws IOException {
        switch (event.getType()) {

            default:
                break;
        }
    }

    /**
     * 同步消息响应线程
     *
     * @param event
     */
    @SuppressWarnings("unchecked")
    public void onEventMainThread(BaseEvents event) {
        switch (event.getType()) {
            case EventsConfig.ALBUM_DETAIL_CLICK://单击页面显示或隐藏页面
                break;
            default:
                break;
        }
    }
}
